let jobAddModule = (function () { 
    let $submit = $('.submit'),
        $jobname = $('.jobname'),
        $jobdesc = $('.jobdesc'),
        $spanjobname = $('.spanjobname'),
        $checkboxList = $('input[type=checkbox]')
    let jobId = null
    function checkName() {
        let val = $jobname.val().trim()
        if (val.length === 0) {
            $spanjobname.html('请输入职务名称')
            return false
        }
        return true
    }
    
    async function submitHandle() {  
        if (!checkName()) return
        let arr = []
        Array.prototype.filter.call($checkboxList, item => {
            if ($(item).prop('checked')) {
                arr.push($(item).val())
            }
        }) 
        let params = {
            name:$jobname.val().trim(),
            desc: $jobdesc.val().trim(),
            power:arr.join('|')
        }
        if (jobId) {
            params.jobId = jobId
            let result =await axios.post('/job/update', params)
            if (result.code == 0) {
                localStorage.removeItem('job')
                alert('修改成功')
                window.location.href = 'joblist.html'
                return
            }
            return
        }
        let result =await axios.post('/job/add', params)
        if (result.code == 0) {
            localStorage.removeItem('job')
            alert('添加成功')
            window.location.href = 'joblist.html'
            return
        }
        alert('添加失败')
    }
    async function queryBaseInfo() {
        let result = await axios.get('/job/info', {
            params: {
                jobId:jobId
            }
        })
        if (result.code == 0) {
            let {name,desc,power} = result.data
            $jobname.val(name)
            $jobdesc.val(desc)
            let arr =[]
            if (power) arr = power.split('|')
            arr.forEach(item => { 
                $(`#${item}`).prop('checked',true)  
            }) 
            return
        }
        alert('当前编辑的职务不存在，请查证！')
        window.location.href='joblist.html'
    }
    return {
        init() {
            let params = window.location.href.queryURLParams()
            if (params.hasOwnProperty('jobId')) {
                jobId = params.jobId
                queryBaseInfo()
            } 

            $jobname.blur(checkName)
            $submit.click(submitHandle)    
        }
    }
})()
jobAddModule.init()